package com.loong.system.controller.backend;

import com.google.common.collect.Lists;
import com.loong.common.mongo.file.MongoFileDO;
import com.loong.common.mongo.file.MongoFileService;
import com.loong.common.mvc.BaseController;
import com.loong.common.rest.Result;
import com.loong.common.utils.FileUtils;
import com.loong.system.common.dto.UploadResultDO;
import com.loong.system.common.dto.UploadResultDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/manage/system/file")
public class BackendFileController extends BaseController {

    @Autowired
    private MongoFileService mongoFileService;

    @GetMapping(path = "/get/{id}")
    public void loadFile(@PathVariable String id, HttpServletResponse response) {
        GridFsResource gridFsResource = mongoFileService.get(id);
        if (ObjectUtils.isEmpty(gridFsResource)) {
            return;
        }
        dealOut(response, gridFsResource);
    }

    private void dealOut(HttpServletResponse response, GridFsResource gridFsResource) {
        try(OutputStream outputStream = response.getOutputStream()) {
            response.setContentType(gridFsResource.getContentType());
            outputStream.write(IOUtils.toByteArray(gridFsResource.getInputStream()));
            outputStream.flush();
        } catch (Exception ex) {
            log.error("/manage/system/file/get error", ex);
        }
    }

    @GetMapping(path = "/download/{id}")
    public void downloadFile(@PathVariable String id, HttpServletResponse response) {
        GridFsResource gridFsResource = mongoFileService.get(id);
        if (ObjectUtils.isEmpty(gridFsResource)) {
            return;
        }
        try {
            String filename = gridFsResource.getFilename();
            log.info("文件名称是{}", filename);
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("/manage/system/file/get error", e);
        }
        dealOut(response, gridFsResource);
    }

    @PostMapping(path = "/upload")
    public Result uploadFile(@RequestParam(name="files", defaultValue="") MultipartFile[] multipartFiles) {
        if (multipartFiles == null || multipartFiles.length <= 0) {
            return Result.fail("上传的文件不能为空");
        }
        try {
            List<UploadResultDO> uploadResult = Lists.newArrayList();
            MongoFileDO mongoFileDO; UploadResultDO uploadResultDO;
            for (MultipartFile multipartFile : multipartFiles) {
                mongoFileDO = new MongoFileDO();
                mongoFileDO.setContentType(multipartFile.getContentType());
                mongoFileDO.setData(multipartFile.getBytes());
                mongoFileDO.setFileName(multipartFile.getOriginalFilename());
                String id = mongoFileService.save(mongoFileDO);
                String typeByName = FileUtils.getTypeByName(multipartFile.getOriginalFilename());
                if(null != typeByName){
                    id = id+"."+typeByName;
                }
                uploadResultDO = new UploadResultDO();
                uploadResultDO.setFileId(id);
                // 改成返回前端的地址 后端nginx配置比较少
                uploadResultDO.setPath(mongoFileService.getFilePath(id, true));
                uploadResult.add(uploadResultDO);
            }
            return Result.success(uploadResult);
        } catch (Exception ex) {
            log.error("/system/file/upload error", ex);
            return Result.fail("上传的文件时发生异常");
        }
    }

}
